package com.zhentao.controller;

import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.avatar-dir}")
    private String avatarDir;

    @RequestMapping("avatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (!contentType.startsWith("image/")) {
                return Result.ERROR("仅支持图片文件上传");
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID() + suffix;

            // 创建目标目录
            Path dirPath = Paths.get(uploadPath, avatarDir);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }

            // 保存文件
            Path filePath = dirPath.resolve(fileName);
            file.transferTo(filePath);

            // 返回访问路径（根据实际访问方式配置）
            String accessUrl = "/uploads/" + avatarDir + fileName;
            return Result.OK().data("url", accessUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.ERROR("文件上传失败");
        }
    }
}